package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"short-video-dev/pkg"
	"short-video-dev/videorpc/videorpc"

	"short-video-dev/api/internal/svc"
	"short-video-dev/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserUpdateLogic) UserUpdate(req *types.UserUpdateRequest, r *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line

	upload := ""
	if req.TypeId == 1 {
		file, m, err := r.FormFile("file")
		if err != nil {
			return &types.Response{
				Message: "文件不存在",
				Code:    500,
				Data:    nil,
			}, nil
		}

		if m.Size > 5*1024*1024 {
			return &types.Response{
				Message: "图片大小<=5MB",
				Code:    500,
				Data:    nil,
			}, nil
		}

		ext := filepath.Ext(m.Filename)
		if ext != ".jpg" && ext != ".png" && ext != ".webp" {
			return &types.Response{
				Message: "图片类型仅支持JPG/PNG/WEBP",
				Code:    500,
				Data:    nil,
			}, nil
		}

		upload, err = pkg.Upload(file, m)
		if err != nil {
			return &types.Response{
				Message: err.Error(),
				Code:    500,
				Data:    nil,
			}, nil
		}
	}

	data, err := l.svcCtx.VideoRpc.UserUpdate(l.ctx, &videorpc.UserUpdateRequest{
		UserId:    req.UserId,
		NikeName:  req.NikeName,
		HeadImage: upload,
	})
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Message: "个人资料修改成功",
		Code:    200,
		Data:    data,
	}, nil
}
